package com.zhiyou100.controller;

import com.zhiyou100.entity.ErrorMessage;
import com.zhiyou100.entity.ResponseEntity;
import com.zhiyou100.exception.ExamException;
import com.zhiyou100.exception.LoginException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 异常控制器
 *
 * @author yang
 * @version 1.0.0
 * @date 2020-09-25 22:26
 */
@ControllerAdvice
public class ExceptionController {
    /**
     * 拦截 ExamException 异常，给前端响应
     *
     * @param e 异常
     * @return 错误信息
     */
    @ExceptionHandler(ExamException.class)
    @ResponseBody
    public ErrorMessage exceptionMessage(Throwable e) {

        return ErrorMessage.builder()
                .statusCode(500)
                .errorCode("B0001")
                .errorMessage("服务器端出错了，原因" + e.getMessage())
                .userPromptMessage("服务器端出错了，请刷新页面！")
                .build();

    }

    /**
     * 拦截 LoginException 登陆异常，给予响应
     *
     * @param e 拦截到的异常
     * @return 响应
     */
    @ExceptionHandler(LoginException.class)
    @ResponseBody
    public ResponseEntity<Object> loginErrorMessage(Throwable e) {
        return ResponseEntity.builder()
                .status(400)
                .message(e.getMessage())
                .build();
    }
}
